from datetime import datetime

from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Max
from django.http import JsonResponse
from django.shortcuts import render, get_object_or_404
from django.utils.dateparse import parse_datetime

from topic_selection_process.models import TopicSelection
from .models import TopicSelection
from bases.models import User
from questions_management.models import ProjectTopic
from django.utils import timezone
import pytz

@login_required(login_url='/login/')
def delete_topic_selection(request, selection_id):
    topic = get_object_or_404(TopicSelection, id=selection_id)
    if request.method == 'POST':
        # 权限判断
        if request.user.role == 'student':
            # 学生只能删除自己的“已申请”记录
            if topic.student != request.user:
                return JsonResponse({'success': False, 'message': '不能删除他人申请'})
            if topic.status not in ['applied', 'rejected']:
                return JsonResponse({'success': False, 'message': '只能删除未提交审核的申请'})

        elif request.user.role == 'teacher':
            # 教师只能删除自己指导的课题下的申请
            if request.user != topic.topic.created_by:
                return JsonResponse({'success': False, 'message': '不能操作非本人指导的课题'})
        elif request.user.role == 'admin':
            pass  # 管理员拥有全部权限
        else:
            return JsonResponse({'success': False, 'message': '无权限操作'})

        # 如果是已批准状态，释放名额
        if topic.status == 'approved':
            topic.topic.current_students -= 1
            topic.topic.save()

        topic.delete()
        return JsonResponse({'success': True, 'message': '删除成功'})
    return JsonResponse({'success': False, 'message': '请求错误'})


@login_required(login_url='/login/')
def topic_view(request):
    # 获取所有选题记录
    queryset = TopicSelection.objects.all().order_by('id')

    # 查询逻辑（根据 GET 参数过滤）
    student_name = request.GET.get('student')
    topic_title = request.GET.get('topic')
    status = request.GET.get('status')
    filter_pending = request.GET.get('filter') == 'pending'

    if student_name:
        queryset = queryset.filter(student__username__icontains=student_name)
    if topic_title:
        queryset = queryset.filter(topic__title__icontains=topic_title)
    if status:
        queryset = queryset.filter(status=status)
    if filter_pending:
        queryset = queryset.filter(status='applied')  # 待审核即状态为 applied 的申请

    if request.user.role =='student':
        queryset = queryset.filter(student=request.user)
    # 分页设置
    paginator = Paginator(queryset, 5)  # 每页显示10条
    page_number = request.GET.get('page')
    try:
        page_obj = paginator.page(page_number)
    except PageNotAnInteger:
        page_obj = paginator.page(1)
    except EmptyPage:
        page_obj = paginator.page(paginator.num_pages)

    # 获取学生和题目列表用于下拉选择
    students = User.objects.filter(role='student')  # 假设角色字段为 role
    topics = ProjectTopic.objects.all()

    return render(request, 'topic.html', {
        'topic': page_obj,
        'students': students,
        'topics': topics,
        'current_page': page_obj.number,
        'total_pages': paginator.num_pages,
    })


@login_required(login_url='/login/')
def create_topic_selection(request):
    if request.method == 'POST':
        student_id = request.POST.get('student')
        topic_id = request.POST.get('topic')
        status = request.POST.get('status')
        approve_time_str = request.POST.get('approve_time')
        comment = request.POST.get('comment')
        max_id = TopicSelection.objects.aggregate(max_id=Max('id'))['max_id'] or 0

        # 新增：判断学生是否已有选题（无论哪个题目）
        student = User.objects.get(id=student_id)
        if TopicSelection.objects.filter(student=student).exists():
            return JsonResponse({
                'success': False,
                'message': '您已有一个选题，不能重复申请'
            })

        if approve_time_str:
            # 使用 parse_datetime 自动识别格式
            dt = parse_datetime(approve_time_str)

            # 只有当 dt 是 naive 时间时才加时区
            if dt and timezone.is_naive(dt):
                dt = timezone.make_aware(dt, timezone=pytz.timezone("Asia/Shanghai"))

            aware_approve_time = dt
        else:
            aware_approve_time = None

        try:
            student = User.objects.get(id=student_id)
            topic = ProjectTopic.objects.get(id=topic_id)

            # 新增验证：如果当前用户是教师，必须确保该题目是他创建的
            if request.user.role == 'teacher' and topic.created_by != request.user:
                return JsonResponse({'success': False, 'message': '不能操作非本人创建的题目'})

            # 校验题目是否还有名额
            if topic.current_students >= topic.max_students:
                return JsonResponse({'success': False, 'message': '该题目已满员，无法申请'})

            TopicSelection.objects.create(
                id=max_id + 1,
                student=student,
                topic=topic,
                status=status,
                approve_time=aware_approve_time or None,
                comment=comment
            )
            # 更新题目当前人数
            if status == 'approved':
                topic.current_students += 1
            topic.save()

            return JsonResponse({'success': True, 'message': '选题创建成功'})
        except Exception as e:
            print(e)
            return JsonResponse({'success': False, 'message': str(e)})
    return JsonResponse({'success': False, 'message': '无效请求'})


@login_required(login_url='/login/')
def update_topic_selection(request, selection_id):
    try:
        selection = TopicSelection.objects.get(id=selection_id)
    except TopicSelection.DoesNotExist:
        return JsonResponse({'success': False, 'message': '选题不存在'})

    if request.method == 'POST':
        if not (request.user.role == 'teacher' or request.user.role == 'admin'):
            return JsonResponse({'success': False, 'message': '权限不足'})
            # 教师权限控制：只能修改自己创建的题目下的选题申请
        if request.user.role == 'teacher':
            # 获取选题对应的题目
            selected_topic = selection.topic

            # 判断是否是自己创建的题目
            if selected_topic.created_by != request.user:
                return JsonResponse({
                    'success': False,
                    'message': '不能操作非本人创建的题目下的申请'
                })

        status = request.POST.get('status')
        comment = request.POST.get('comment')

        # 如果是批准，则检查是否超过最大人数限制
        if status == 'approved':
            if selection.topic.current_students >= selection.topic.max_students:
                return JsonResponse({'success': False, 'message': '该题目已满员，无法批准'})
                # 如果是从其他状态变为批准，增加题目人数计数器
            if selection.status != 'approved':
                selection.topic.current_students += 1
            selection.topic.save()
            # 如果是从批准状态变为未通过，减少题目人数计数器
        elif status == 'rejected':
            selection.topic.current_students -= 1
            selection.topic.save()
        # 更新选题状态和评论
        selection.status = status
        selection.comment = comment
        # 如果是驳回操作，设置审核时间为当前时间
        if status == 'rejected':
            selection.approve_time = timezone.now()
        selection.save()

        return JsonResponse({'success': True, 'message': '状态更新成功'})
    return JsonResponse({'success': False, 'message': '无效请求'})
